package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public ResultInfo login(String username, String password) {
        //根据username从数据库查询,如果查询不到,返回用户名不存在
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null){
            return ResultInfo.error("用户名不存在");
        }
        //比对密码,比对失败,返回密码错误
        String passwordWhitMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWhitMd5,employee.getPassword())){
            return ResultInfo.error("密码错误");
        }
        //确定员工状态status 1正常 0禁用 ,如果非正常状态,返回用户被禁用
        if (employee.getStatus() == Employee.STATUS_DISABLE){
            return ResultInfo.error("用户被禁用");
        }
        //没问题返回成功
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }

    @Override
    public void save(Employee employee) {
     //补齐参数
        //雪花算法
        employee.setId(IdUtil.getSnowflake(1,1).nextId());
        //设置加密默认密码
        employee.setPassword(SecureUtil.md5("123"));
        //设置默认状态
        employee.setStatus(Employee.STATUS_ENABLE);
//        //创建时间
//        employee.setCreateTime(new Date());
//        //修改时间
//        employee.setUpdateTime(new Date());
//        //创建人
//        employee.setCreateUser(1L);
//        //修改人
//        employee.setUpdateUser(1L);

        //调用mapper
        employeeMapper.save(employee);

    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }

    @Override
    public void update(Employee employee) {
        //重新赋值
//        employee.setUpdateTime(new Date());
//        employee.setUpdateUser(1L);
        //调用mapper执行修改
        employeeMapper.update(employee);
    }


}
